import React, { useEffect, useRef, useState, useCallback } from 'react';
import { listen, UnlistenFn } from '@tauri-apps/api/event';
import { TerminalComponentProps } from '../types';

export function TerminalSimple({
  terminal,
  onInput,
  onResize,
  onClose,
  onRename,
}: TerminalComponentProps) {
  const [output, setOutput] = useState<string>('');
  const [isEditing, setIsEditing] = useState(false);
  const [editName, setEditName] = useState(terminal.name || '');
  const [currentInput, setCurrentInput] = useState('');
  const terminalRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLTextAreaElement>(null);
  const unlistenFn = useRef<UnlistenFn | null>(null);

  // Listen for terminal output
  useEffect(() => {
    const setupListener = async () => {
      unlistenFn.current = await listen(
        `riterm://terminal-output-${terminal.sessionId}`,
        (event) => {
          const { data } = event.payload;
          const text = new TextDecoder().decode(new Uint8Array(data));
          setOutput(prev => prev + text);
        }
      );
    };

    setupListener();

    return () => {
      if (unlistenFn.current) {
        unlistenFn.current();
      }
    };
  }, [terminal.sessionId]);

  // Auto-scroll to bottom when new output arrives
  useEffect(() => {
    if (terminalRef.current) {
      terminalRef.current.scrollTop = terminalRef.current.scrollHeight;
    }
  }, [output]);

  // Handle input
  const handleInputChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setCurrentInput(e.target.value);
  }, []);

  // Handle key presses
  const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      const value = currentInput;
      if (value.trim()) {
        const data = Array.from(new TextEncoder().encode(value + '\n'));
        onInput(terminal.sessionId, data);
        setCurrentInput('');
      }
    }
  }, [currentInput, terminal.sessionId, onInput]);

  // Handle rename
  const handleRename = useCallback(() => {
    if (isEditing) {
      onRename(terminal.sessionId, editName.trim() || undefined);
      setIsEditing(false);
    } else {
      setIsEditing(true);
      setEditName(terminal.name || '');
    }
  }, [isEditing, editName, terminal.sessionId, terminal.name, onRename]);

  const handleRenameKeyDown = useCallback((e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleRename();
    } else if (e.key === 'Escape') {
      setIsEditing(false);
      setEditName(terminal.name || '');
    }
  }, [handleRename, terminal.name]);

  // Get status color
  const getStatusColor = useCallback(() => {
    switch (terminal.status) {
      case 'active':
        return 'text-green-500';
      case 'closed':
      case 'terminated':
        return 'text-red-500';
      case 'error':
        return 'text-red-600';
      default:
        return 'text-gray-500';
    }
  }, [terminal.status]);

  return (
    <div className="terminal bg-black text-green-400 font-mono text-sm rounded-lg overflow-hidden border border-gray-700">
      {/* Header */}
      <div className="flex items-center justify-between bg-gray-800 px-3 py-2 border-b border-gray-700">
        <div className="flex items-center space-x-2">
          <div className={`w-2 h-2 rounded-full ${
            terminal.status === 'active' ? 'bg-green-500' : 'bg-red-500'
          }`} />
          {isEditing ? (
            <input
              type="text"
              value={editName}
              onChange={(e) => setEditName(e.target.value)}
              onKeyDown={handleRenameKeyDown}
              onBlur={handleRename}
              className="bg-gray-700 text-white px-2 py-1 rounded text-sm"
              placeholder="Terminal name..."
              autoFocus
            />
          ) : (
            <span
              className="text-white cursor-pointer hover:text-gray-300"
              onClick={handleRename}
              title="Click to rename"
            >
              {terminal.name || terminal.sessionId}
            </span>
          )}
          <span className={`text-xs ${getStatusColor()}`}>
            ({terminal.status})
          </span>
        </div>

        <div className="flex items-center space-x-2">
          <span className="text-xs text-gray-400">
            {terminal.size.rows}x{terminal.size.cols}
          </span>
          <button
            onClick={() => onClose(terminal.sessionId)}
            className="text-red-400 hover:text-red-300 transition-colors"
            title="Close terminal"
          >
            ✕
          </button>
        </div>
      </div>

      {/* Terminal output */}
      <div
        ref={terminalRef}
        className="h-96 overflow-y-auto p-3 whitespace-pre-wrap"
        style={{ minHeight: '384px' }}
      >
        <div className="text-green-400">
          {output || <span className="text-gray-500">Terminal output will appear here...</span>}
        </div>
      </div>

      {/* Terminal input */}
      {terminal.status === 'active' && (
        <div className="border-t border-gray-700 p-2">
          <div className="flex items-start space-x-2">
            <span className="text-green-400">$</span>
            <textarea
              ref={inputRef}
              value={currentInput}
              onChange={handleInputChange}
              onKeyDown={handleKeyDown}
              placeholder="Type commands here... (Enter to send, Shift+Enter for new line)"
              className="flex-1 bg-gray-800 text-green-400 p-2 rounded resize-none focus:outline-none focus:ring-1 focus:ring-green-500 min-h-[60px]"
              rows={3}
              spellCheck={false}
            />
          </div>
        </div>
      )}
    </div>
  );
}